<template>
  <div style="display: flex; height: 100%">
    <el-container>
      <!-- 左侧用户组列表 -->
      <div style="width: 60%; border-right: 1px solid #ccc; padding: 5px">
        <el-header>
          <el-form :inline="true" :model="searchForm" class="demo-form-inline" @submit.prevent>
            <el-form-item label="用户组">
              <el-input v-model="searchForm.name" placeholder="用户组" @keyup.enter="onSearch"/>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSearch">查询</el-button>
              <el-button type="default" @click="onReset">重置</el-button>
              <el-button type="default" @click="onAddGroup" icon="CirclePlus"
                >新增用户组</el-button
              >
            </el-form-item>
          </el-form>
        </el-header>
        <el-divider direction="horizontal" style="width: 95%"></el-divider>
        <el-table
          :data="groupList"
          @row-click="handleGroupClick"
          style="width: 100%"
        >
          <el-table-column prop="id" label="ID" v-if="false" />
          <el-table-column prop="name" label="名称" />
          <el-table-column prop="description" label="描述" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button link type="primary" @click="onEditGroup(scope.row)"
                >编辑</el-button
              >
              <el-button link type="primary" @click="onDeleteGroup(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="listTotal"
        />
      </div>
      <!-- 右侧用户列表 -->
      <div style="width: 40%; padding: 5px">
        <el-text class="cus-title">{{
          selectedGroup.name ? selectedGroup.name : ""
        }}</el-text>
        <el-divider direction="vertical"></el-divider>
        <el-button type="default" @click="onAddUserToGroup" icon="CirclePlus"
          >添加用户</el-button
        >
        <el-divider direction="horizontal" style="width: 95%"></el-divider>
        <el-table :data="selectedGroupUsers">
          <el-table-column prop="id" label="ID" v-if="false" />
          <el-table-column prop="username" label="用户名" />
          <el-table-column prop="fullname" label="姓名" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="removeUserFromGroup(scope.row)"
                >移除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-container>
  </div>
  <el-dialog v-model="showAddUserToGroupDialog" title="加入用户" header-class="dialog-custom-header">
    <el-divider direction="horizontal" style="width: 95%"></el-divider>
    <el-form :inline="true" :model="searchUserForm" class="demo-form-inline">
      <el-form-item label="用户名" class="search-input-item">
        <el-input v-model="searchUserForm.username" placeholder="用户名" />
      </el-form-item>
      <el-form-item class="search-input-item">
        <el-button type="primary" @click="onSearchUser" icon="Search"
          >查询</el-button
        >
      </el-form-item>
    </el-form>
    <el-divider direction="horizontal" style="width: 95%"></el-divider>
    <el-table :data="userList">
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="fullname" label="用户姓名" />
      <el-table-column prop="phone" label="手机号" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button link type="primary" @click="addUserToGroup(scope.row)"
            >添加</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>
  <el-dialog
    v-model="groupDialogVisible"
    :title="isEditGroup ? '修改用户组' : '新增用户组'"
    width="30%"
    header-class="dialog-custom-header"

  >
  <el-divider direction="horizontal" style="width: 95%"></el-divider>
  <el-form :model="newGroupForm">
      <el-form-item label="名称">
        <el-input v-model="newGroupForm.name" :disabled="isEditGroup" />
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="newGroupForm.description" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="groupDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="onSubmitGroup">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from "vue";
import { get, post, put, del } from "@/utils/request";
const groupDialogVisible = ref(false);
const isEditGroup = ref(false);
const listTotal = ref(0);
const userList = ref([]);
const currentPage = ref(1); // 当前页码
const pageSize = ref(10); // 每页显示的数量
const groupList = ref([]);
const newGroup = ref({
  name: "",
  description: "",
}); // 新增用户组数据
const searchForm = reactive({
  name: null,
});
const showAddGroupDialog = ref(false); // 新增用户组对话框显示状态
const editingGroup = ref({}); // 编辑用户组数据
const showEditGroupDialog = ref(false); // 编辑用户组对话框显示状态
const selectedGroupUsers = ref([]);
const selectedGroup = reactive({
  id: null,
  name: null,
  description: null,
  users: [],
});
const searchUserForm = reactive({
  username: null,
});

const showAddUserToGroupDialog = ref(false); // 加入用户对话框显示状态
const users = ref([]); // 用户列表数据
const newGroupForm = reactive({
  id: null,
  name: null,
  description: null,
});
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  onSearch();
};
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  onSearch();
};
const onSearchUser = async () => {
  let params = {
    username: searchUserForm.username,
    page: 1,
    size: 100,
  };
  await get("/cam/users", params)
    .then((res) => {
      if (res.data.code === 0) {
        let fullUserList = res.data.data.data;
        userList.value = fullUserList.filter((item) => {
          return !selectedGroupUsers.value.some((u) => u.id === item.id);
        });
      } else if (res.data.code === 401) {
        sessionStorage.clear();
        window.location.assign("/login");
      } else {
        ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
      }
    })
    .catch((e) => {
      ElMessage.error(e.message);
    });
};
const onSearch = () => {
  // console.log("搜索条件:", searchForm);
  let params = {
    name: searchForm.name,
    page: currentPage.value,
    size: pageSize.value,
  };
  get("/cam/groups", params)
    .then((res) => {
      // console.log("搜索结果:", res);
      if (res.data.code === 0) {
        groupList.value = res.data.data.data;
        listTotal.value = res.data.data.total;
      } else if (res.data.code === 401) {
        sessionStorage.clear();
        window.location.assign("/login");
      } else {
        ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
      }
    })
    .catch((e) => {
      ElMessage.error(e.message);
    });
};

const onReset = () => {
  searchForm.name = null;
};

const onAddGroup = () => {
  Object.keys(newGroupForm).forEach((key) => {
    newGroupForm[key] = null;
  });
  isEditGroup.value = false;
  groupDialogVisible.value = true;
};

const handlePageChange = (page) => {
  currentPage.value = page;
};

const onSubmitGroup = async() => {
  let succ = false;
  if (isEditGroup.value) {
    // 修改用户组
    let payload = {
      name: newGroupForm.name,
      description: newGroupForm.description,
    };
    await put("/cam/groups/" + newGroupForm.id, payload)
      .then((res) => {
        // console.log("搜索结果:", res);
        if (res.data.code === 0) {
          onSearch();
          succ = true;
          ElMessage.success("修改成功");
        } else if (res.data.code === 401) {
          sessionStorage.clear();
          window.location.assign("/login");
        } else {
          ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
        }
      })
      .catch((e) => {
        ElMessage.error(e.message);
      });
    groupDialogVisible.value = false;
  } else {
    // 新增用户组
    let payload = {
      name: newGroupForm.name,
      description: newGroupForm.description,
    };
    await post("/cam/groups", payload)
      .then((res) => {
        // console.log("搜索结果:", res);
        if (res.data.code === 0) {
          newGroupForm.id = res.data.data.id;
          onSearch();
          succ = true;
          ElMessage.success("新增成功");
        } else if (res.data.code === 401) {
          sessionStorage.clear();
          window.location.assign("/login");
        } else {
          ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
        }
      })
      .catch((e) => {
        ElMessage.error(e.message);
      });
  }
  if (succ) {
    groupDialogVisible.value = false;
  }
};

const onEditGroup = (group) => {
  // 编辑用户组逻辑
  // editingGroup.value = { ...group };
  isEditGroup.value = true;
  Object.assign(newGroupForm, group);
  groupDialogVisible.value = true;
};

const updateGroup = () => {
  // 更新用户组逻辑
  // const index = groups.value.findIndex(
  //   (group) => group.id === editingGroup.value.id
  // );
  // if (index !== -1) {
  //   groups.value[index] = { ...editingGroup.value };
  // }
  groupDialogVisible.value = false;
};

const onDeleteGroup = (group) => {
  // 删除用户组逻辑
  // groups.value = groups.value.filter((g) => g.id !== group.id);
};

const handleGroupClick = (group) => {
  // 根据用户组ID获取用户列表
  Object.assign(selectedGroup, group);
  get("/cam/groups/" + selectedGroup.id)
    .then((res) => {
      // console.log("搜索结果:", res);
      if (res.data.code === 0) {
        selectedGroupUsers.value = res.data.data.users;
      } else if (res.data.code === 401) {
        sessionStorage.clear();
        window.location.assign("/login");
      } else {
        ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
      }
    })
    .catch((e) => {
      ElMessage.error(e.message);
    });
};

const onAddUserToGroup = () => {
  // 确定有选中的组
  if (!selectedGroup.id) {
    ElMessage.error("请选择一个用户组");
    return;
  }
  userList.value = []
  showAddUserToGroupDialog.value = true;
};
const addUserToGroup = (user) => {
  // 添加用户到用户组逻辑
  let payload = {
    users: [user.id],
  };
  post("/cam/groups/" + selectedGroup.id + "/users", payload)
    .then((res) => {
      // console.log("搜索结果:", res);
      if (res.data.code === 0) {
        if (!selectedGroupUsers.value.some((u) => u.id === user.id)) {
          selectedGroupUsers.value.push(user);
        }
        userList.value = userList.value.filter((u) => u.id !== user.id);
        ElMessage.success("添加成功");
      } else if (res.data.code === 401) {
        sessionStorage.clear();
        window.location.assign("/login");
      } else {
        ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
      }
    })
    .catch((e) => {
      ElMessage.error(e.message);
    });
};

const removeUserFromGroup = (user) => {
  // 移除用户逻辑
  // 添加用户到用户组逻辑
  let payload = {
    users: [user.id],
  };
  del("/cam/groups/" + selectedGroup.id + "/users", payload)
    .then((res) => {
      // console.log("搜索结果:", res);
      if (res.data.code === 0) {
        selectedGroupUsers.value = selectedGroupUsers.value.filter(
          (u) => u.id !== user.id
        );
        ElMessage.success("添加成功");
      } else if (res.data.code === 401) {
        sessionStorage.clear();
        window.location.assign("/login");
      } else {
        ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
      }
    })
    .catch((e) => {
      ElMessage.error(e.message);
    });
};

onMounted(() => {
  onSearch();
});
</script>

<style scoped>
.role-assignment-container {
  display: flex;
  justify-content: space-between;
}

.left-panel,
.right-panel {
  width: 48%;
}

.search-input {
  margin-bottom: 10px;
}

.role-table {
  width: 100%;
}

.dialog-footer {
  text-align: right;
}
.el-dialog__header.dialog-custom-header {
  padding-bottom: 0px; /* 自定义头部内边距 */
}
.search-input-item {
  margin-bottom: 0px;
}
</style>
